from ._base import BaseModel
from ..extends.flask_sqlalchemy import db
from ..extends.flask_login import login_manager
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash


@login_manager.user_loader
def _load_user(user_id):
    return User.query.get(user_id)


class User(BaseModel, UserMixin):
    account = db.Column(db.String(100), nullable=False, comment='账号名称')
    _password_hash = db.Column('password', db.String(128), nullable=False, comment='账号密码')
    name = db.Column(db.String(6), nullable=False, default='', comment='姓名')
    identity_card = db.Column(db.String(18), nullable=False, default='', comment='身份证号码')
    phone_number = db.Column(db.String(11), nullable=False, default='', comment='手机号码')

    notifications = db.relationship(
        'Notification',
        foreign_keys="Notification.receiver_id",
        primaryjoin="Notification.receiver_id == User.id",
        cascade='all'
    )

    @property
    def is_full(self):
        if self.name == '' or self.identity_card == '' or self.phone_number == '':
            return False
        return True

    @property
    def status_text(self):
        if self.status == 0:
            return '锁定'
        return '正常' if self.is_full else '待用户完善'

    @property
    def password(self):
        return self._password_hash

    @password.setter
    def password(self, secure):
        self._password_hash = generate_password_hash(secure)

    def check_password(self, secure):
        return check_password_hash(self.password, secure)


class Notification(BaseModel):
    message = db.Column(db.Text)
    is_read = db.Column(db.Boolean, default=False)
    receiver_id = db.Column(db.Integer, index=True, nullable=False, comment='用户id')
    receiver = db.relationship(
        'User',
        foreign_keys="Notification.receiver_id",
        primaryjoin="Notification.receiver_id == User.id",
    )
